package com.rbcs.reimb.webapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.base.currency.service.CurrencyManager;
import com.rbcs.base.currency.service.ExchangeRateManager;
import com.rbcs.base.model.Currency;
import com.rbcs.base.model.ExchangeRate;
import com.rbcs.base.model.Item;
import com.rbcs.base.model.Project;
import com.rbcs.base.model.ProjectType;
import com.rbcs.base.project.service.ProjectManager;
import com.rbcs.base.project.service.ProjectTypeManager;
import com.rbcs.flow.FlowConstants;
import com.rbcs.reimb.ReimbConstants;
import com.rbcs.reimb.model.Reimb;
import com.rbcs.reimb.model.ReimbDetail;
import com.rbcs.reimb.service.ReimbDetailManager;
import com.rbcs.reimb.service.ReimbManager;
import com.systop.common.modules.dept.model.Dept;
import com.systop.common.modules.dept.service.DeptManager;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.ApplicationException;
import com.systop.core.Constants;
import com.systop.core.dao.support.Page;
import com.systop.core.util.DateUtil;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.JsonCrudAction;

/**
 * 报销申请管理Action
 * 
 * @author ShangHua
 */
@SuppressWarnings({ "serial", "unchecked", "rawtypes" })
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ReimbAction extends JsonCrudAction<Reimb, ReimbManager> {

	// 部门管理Manager
	@Autowired
	private DeptManager deptManager;

	// 项目管理Manager
	@Autowired
	private ProjectManager projectManager;

	// 部门类型Manager
	@Autowired
	private ProjectTypeManager projectTypeManager;

	// 币种类型Manager
	@Autowired
	private CurrencyManager currencyManager;

	// 币种汇率Manager
	@Autowired
	private ExchangeRateManager exchangeRateManager;

	// JSON数据
	private Map<String, String> jsonResult;

	// 开始时间
	private Date startDate;

	// 结束时间
	private Date endDate;

	// 报销人Id
	private Integer reimberId;

	// 项目Id
	private Integer projectId;

	/**
	 * 报销明细管理Manager
	 */
	@Autowired
	private ReimbDetailManager reimbDetailManager;

	// 项目类别List
	private List<ProjectType> projectTypes;

	// 项目类别ID
	private Integer projectTypeId;

	private Integer parentReimbId;

	/**
	 * 查询当前登录用户创建的报销申请单
	 */
	public String index() {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		StringBuffer hql = new StringBuffer(
				"from Reimb r where r.parentReimb is null ");
		List args = new ArrayList();
		User user = UserUtil.getPrincipal(getRequest());
		if (user != null) {
			hql.append("and r.reimber.id = ?");
			args.add(user.getId());
		}

		if (StringUtils.isNotBlank(getModel().getSingleNo())) {
			hql.append("and r.singleNo like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getSingleNo()));
		}

		if (StringUtils.isNotBlank(getModel().getAudStatus())) {
			hql.append("and b.audStatus = ? ");
			args.add(getModel().getAudStatus());
		}

		if (StringUtils.isNotBlank(getModel().getPayStatus())) {
			hql.append("and r.payStatus = ? ");
			args.add(getModel().getPayStatus());
		}

		commonDateCondition(hql, args);

		hql.append("order by r.createDate desc");
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);

		return INDEX;
	}

	/**
	 * 查询当前登录用户创建的报销申请单
	 */
	public String childIndex() {
		if (parentReimbId != null) {
			Page page = PageUtil.getPage(getPageNo(), getPageSize());
			StringBuffer hql = new StringBuffer(
					"from Reimb r where r.parentReimb is not null ");
			List args = new ArrayList();
			hql.append("and r.parentReimb.id = ?");
			args.add(parentReimbId);
			hql.append("order by r.createDate");
			page = getManager().pageQuery(page, hql.toString(), args.toArray());
			restorePageData(page);

			List<Reimb> childReimbs = page.getData();
			double childReimbTotal = 0;
			for (Reimb reimb : childReimbs) {
				childReimbTotal = childReimbTotal + reimb.getAmount();
			}
			getRequest().setAttribute("childReimbTotal", childReimbTotal);
		}
		return "childIndex";
	}

	/**
	 * 公共的日期查询条件
	 * 
	 * @param hql
	 * @param args
	 */
	private void commonDateCondition(StringBuffer hql, List<Object> args) {
		if (startDate != null) {
			hql.append("and r.createDate >= ? ");
			args.add(startDate);
		}
		if (endDate != null) {
			hql.append("and r.createDate <= ? ");
			args.add(endDate);
		}
	}

	/**
	 * 新建报销单信息
	 */
	@Override
	public String edit() {
		if (getModel().getId() == null) {
			getModel().setCreateDate(new Date());
			getModel().setDept(getLoginUserDept());
			String singleNo = DateUtil.getDateTime("yyyyMMddHHmmss", new Date());
			getModel().setSingleNo(ReimbConstants.REIMB_SINGLE_PREFIX + singleNo);
		}
		projectTypes = projectTypeManager.getTypes();
		getModel().setBorrowAmount(null);
		getModel().setTotalBorrowIds(null);
		getModel().setTotalBorrowNos(null);
		getModel().setPartBorrowIds(null);
		getModel().setPartBorrowNos(null);
		return super.edit();
	}

	/**
	 * 新建父报销单信息
	 */
	@Transactional
	public String editParent() {
		if (getModel().getId() == null && parentReimbId == null) {
			User user = UserUtil.getPrincipal(getRequest());
			getModel().setReimber(user);
			getModel().setCreateDate(new Date());
			getModel().setDept(getLoginUserDept());
			String singleNo = DateUtil.getDateTime("yyyyMMddHHmmss", getModel().getCreateDate());
			getModel().setSingleNo(ReimbConstants.REIMB_SINGLE_PREFIX + singleNo);
			getModel().setSingleType(ReimbConstants.SINGLE_TYPE_PARENTREIMB);
			getModel().setAudStatus(FlowConstants.AUDIT_UNSEND);
			getModel().setPayStatus(Constants.NO);
			getModel().setAmount(0.0);
			getModel().setBorrowAmount(0.0);
			getModel().setBalance(0.0);
			getManager().save(getModel());
		}
		getModel().setBorrowAmount(null);
		getModel().setTotalBorrowIds(null);
		getModel().setTotalBorrowNos(null);
		getModel().setPartBorrowIds(null);
		getModel().setPartBorrowNos(null);
		return "editParent";
	}

	/**
	 * 新建父报销单信息
	 */
	public String editChild() {
		if (getModel().getId() == null) {
			if (parentReimbId != null) {
				getModel().setCreateDate(new Date());
				Reimb reimb = getManager().get(parentReimbId);
				int reimbChilds = reimb.getChildReimbs().size() + 1;
				getModel().setSingleNo(reimb.getSingleNo() + "_" + reimbChilds);
			}
		}
		projectTypes = projectTypeManager.getTypes();
		return "editChild";
	}

	/**
	 * 保存父报销单信息
	 */
	@Transactional
	public String saveParent() {
		return super.save();
	}

	/**
	 * 【AJAX调用】
	 * @return
	 */
	public String saveChildAjax() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		String id = getRequest().getParameter("id");
		String parentReimbId = getRequest().getParameter("parentReimbId");
		Reimb reimb;
		try {
			if (StringUtils.isNotBlank(id)) {
				reimb = getManager().get(Integer.valueOf(id));
			} else {
				reimb = new Reimb();
				User user = UserUtil.getPrincipal(getRequest());
				reimb.setReimber(user);
				reimb.setCreateDate(new Date());
				reimb.setSingleType(ReimbConstants.SINGLE_TYPE_CHILDREIMB);
				reimb.setAudStatus(FlowConstants.AUDIT_UNSEND);
				if (StringUtils.isNotBlank(parentReimbId)) {
					reimb.setParentReimb(getManager().get(Integer.valueOf(parentReimbId)));
				}
			}
				String singleNo = getRequest().getParameter("singleNo");
				reimb.setSingleNo(singleNo);
				String parentDeptId = getRequest().getParameter("parentDeptId");
				if (StringUtils.isNotBlank(parentDeptId)) {
					Dept dept = getManager().getDao().get(Dept.class, Integer.valueOf(parentDeptId));
					reimb.setDept(dept);
				}

				String projectId = getRequest().getParameter("projectId");
				if (StringUtils.isNotBlank(projectId)) {
					Project project = getManager().getDao().get(Project.class, Integer.valueOf(projectId));
					reimb.setProject(project);
				}
				String reimbTotal = getRequest().getParameter("reimbTotal");
				
				if (StringUtils.isNotBlank(reimbTotal)) {
					reimb.setAmount(Double.parseDouble(reimbTotal));
					reimb.setBalance(Double.parseDouble(reimbTotal));
				} else {
					reimb.setAmount(Double.parseDouble("0"));
					reimb.setBalance(Double.parseDouble("0"));
				}
				
				String itemId = this.getRequest().getParameter("itemIds");
				String title = this.getRequest().getParameter("titles");
				String amount = this.getRequest().getParameter("amounts");
				String exchangeAmount = this.getRequest().getParameter("exchangeAmounts");
				String cId = this.getRequest().getParameter("cIds");
        				
				if (StringUtils.isNotBlank(itemId)) {
					String[] itemIds = itemId.split(",");
					String[] titles = title.split(",");
					String[] amounts = amount.split(",");
					String[] exchangeAmounts = exchangeAmount.split(",");
					String[] cIds = cId.split(",");
					List<ReimbDetail> rdList = new ArrayList<ReimbDetail>();
					for (int i = 0; i < itemIds.length; i++) {
						ReimbDetail rd = new ReimbDetail();						
						if (StringUtils.isNotBlank(titles[i].trim())) {
							rd.setTitle(titles[i].trim());
						} else {
							rd.setTitle(StringUtils.EMPTY);
						}
						
						if (StringUtils.isNotBlank(itemIds[i])) {
							Item item = getManager().getDao().get(Item.class, Integer.valueOf(itemIds[i]));
							rd.setItem(item);
						}
						if (StringUtils.isNotBlank(amounts[i])) {
							rd.setAmount(Double.parseDouble(amounts[i]));
						} else {
							rd.setAmount(Double.parseDouble("0"));
						}
						if (StringUtils.isNotBlank(exchangeAmounts[i].trim())) {
							rd.setExchangeAmount(Double.parseDouble(exchangeAmounts[i].trim()));
						} else {
							rd.setExchangeAmount(Double.parseDouble("0"));
						}

						if (StringUtils.isNotBlank(cIds[i].trim())) {
							String currencyId = cIds[i].split(",")[0].trim();
							if (StringUtils.isNotBlank(currencyId)) {
								Currency currency = getManager().getDao().get(Currency.class, Integer.valueOf(currencyId));
								rd.setCurrency(currency);
							}
						}
						rd.setReimb(reimb);
						rdList.add(rd);						
					}
					this.getManager().save(reimb, rdList);
					jsonResult.put("result", "success");
			}
		} catch (Exception e) {
			jsonResult.put("result", "failure");
			e.printStackTrace();
		}
		return "jsonResult";
	}

	/**
	 * 删除报销单以及相关的详单信息
	 */
	public String removeChild() {
		if (getModel().getId() != null) {
			Reimb reimb = getManager().get(getModel().getId());
			getManager().reimbRemove(reimb);
		}
		return "removeChild";
	}

	/**
	 * 保存报销单信息
	 */
	@Override
	public String save() {
		User user = UserUtil.getPrincipal(getRequest());
		if (user != null) {
			getModel().setReimber(user);
		} else {
			this.addActionMessage("当前登录用户信息不存在，请您重新登录系统！");
			return INPUT;
		}
		try {
			if (getModel().getId() == null) {
				getModel().setCreateDate(new Date());
				getModel().setSingleType(ReimbConstants.SINGLE_TYPE_REIMB);
				getModel().setAudStatus(FlowConstants.AUDIT_UNSEND);
				getModel().setPayStatus(Constants.NO);
				getModel().setPayStatus(Constants.NO);
				getModel().setDept(getLoginUserDept());
			}

			String projectId = getRequest().getParameter("projectId");
			if (StringUtils.isNotBlank(projectId)) {
				Project project = getManager().getDao().get(Project.class,
						Integer.valueOf(projectId));
				getModel().setProject(project);
			}

			// 冲抵部分借款金额
			if (StringUtils.isNotBlank(getModel().getPartBorrowIds())) {
				Double offsetAmount = getModel().getAmount()
						- parseDouble(getModel().getTotalNoRepayAmounts());
				if (offsetAmount > 0) {
					getModel().setOffsetAmount(offsetAmount);
				}
			} else {
				getModel().setOffsetAmount(0.0);
			}

			// 保存报销申请明细
			String[] titles = this.getRequest().getParameterValues("title");
			String[] itemIds = this.getRequest().getParameterValues("itemId");
			String[] amounts = this.getRequest().getParameterValues("amount");
			String[] exchangeAmounts = this.getRequest().getParameterValues(
					"exchangeAmount");
			String[] currencyIds = this.getRequest().getParameterValues("cId");

			List<ReimbDetail> rdList = new ArrayList<ReimbDetail>();

			for (int i = 1; i < itemIds.length; i++) {
				ReimbDetail rd = new ReimbDetail();
				rd.setTitle(titles[i]);
				if (StringUtils.isNotBlank(itemIds[i])) {
					Item item = getManager().getDao().get(Item.class,
							Integer.valueOf(itemIds[i]));
					rd.setItem(item);
				}
				if (StringUtils.isNotBlank(amounts[i])) {
					rd.setAmount(Double.parseDouble(amounts[i]));
				} else {
					rd.setAmount(Double.parseDouble("0"));
				}
				if (StringUtils.isNotBlank(exchangeAmounts[i])) {
					rd.setExchangeAmount(Double.parseDouble(exchangeAmounts[i]));
				} else {
					rd.setExchangeAmount(Double.parseDouble("0"));
				}

				if (StringUtils.isNotBlank(currencyIds[i])) {
					String currencyId = currencyIds[i].split(",")[0];
					if (StringUtils.isNotBlank(currencyId)) {
						Currency currency = getManager().getDao().get(Currency.class,
								Integer.valueOf(currencyId));
						rd.setCurrency(currency);
					}
				}
				rd.setReimb(getModel());
				rdList.add(rd);
			}
			this.getManager().save(getModel(), rdList);
			return SUCCESS;
		} catch (Exception e) {
			addActionError(e.getMessage());
			return INPUT;
		}
	}

	/**
	 * 类型转换
	 * 
	 * @param obj
	 * @return
	 */
	private double parseDouble(Double obj) {
		if (obj != null) {
			return obj;
		}
		return 0.00;
	}

	/**
	 * 把报销明细传到页面
	 */
	public List<ReimbDetail> getReimbDetail() {
		List<ReimbDetail> rd = reimbDetailManager.getDetails(getModel().getId());
		this.getRequest().setAttribute("reimbDetail", rd);
		return rd;
	}

	/**
	 * 发送报销申请到流程表【AJAX调用】
	 * @return
	 */
	public String sendApply() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		String reimbId = getRequest().getParameter("reimbId");
		if (StringUtils.isNotBlank(reimbId)) {
			Reimb reimb = getManager().get(Integer.valueOf(reimbId));
			// 判断是需要部门审批还是项目审批
			if (reimb.getProject() != null) {
				// 判断是否有项目负责人
				String managerName = projectManager.checkProjectManager(reimb
						.getProject().getId());
				if (StringUtils.isNotBlank(managerName)) {
					jsonResult.put("result", "【" + managerName + "】没有项目负责人,不能发送申请！");
					return "jsonResult";
				}
			} else {
				// 判断级联的部门是否有部门负责人
				List<Dept> depts = deptManager.getDeptsBySerialNo(getLoginUserDept()
						.getSerialNo());
				String deptName = deptManager.checkManagerUser(depts);
				if (StringUtils.isNotBlank(deptName)) {
					deptName = deptName.substring(0, deptName.length() - 1);
					jsonResult.put("result", "【" + deptName + "】没有部门负责人,不能发送申请！");
					return "jsonResult";
				}
			}
			try {
				getManager().saveFlows(reimb);
				jsonResult.put("result", "success");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonResult.put("result", "报销申请发送失败！");
		}
		return "jsonResult";
	}

	/**
	 * 发送主报销申请下的各个子报销单到流程表【AJAX调用】
	 * @return
	 */
	public String sendMoreApply() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		String reimbId = getRequest().getParameter("reimbId");
		if (StringUtils.isNotBlank(reimbId)) {
			Reimb reimb = getManager().get(Integer.valueOf(reimbId));
			StringBuffer errorInfo = new StringBuffer();
      if (reimb.getChildReimbs().size() > 0 ) {
      	for (Reimb reimbChild : reimb.getChildReimbs()) {
    			// 判断是需要部门审批还是项目审批
    			if (reimbChild.getProject() != null) {
    				// 判断是否有项目负责人
    				String managerName = projectManager.checkProjectManager(reimbChild.getProject().getId());
    				if (StringUtils.isNotBlank(managerName)) {
    					errorInfo.append("【" + managerName + "】没有项目负责人,不能发送申请！");
    				}
    			} else {
    				// 判断级联的部门是否有部门负责人
    				List<Dept> depts = deptManager.getDeptsBySerialNo(reimbChild.getDept().getSerialNo());
    				String deptName = deptManager.checkManagerUser(depts);
    				if (StringUtils.isNotBlank(deptName)) {
    					deptName = deptName.substring(0, deptName.length() - 1);
    					errorInfo.append("【" + deptName + "】没有部门负责人,不能发送申请！");
    				}
    			}  	
      	}
      	if (StringUtils.isNotBlank(errorInfo.toString())) {
        	jsonResult.put("result", errorInfo.toString());
      	} else {
      		for (Reimb reimbChild : reimb.getChildReimbs()) {
      			getManager().saveFlows(reimbChild);
      		}  
      		reimb.setAudStatus(FlowConstants.AUDIT_PENDING);
      		getManager().save(reimb);
      		jsonResult.put("result", "success");
      	}
      }
		} else {
			jsonResult.put("result", "报销申请发送失败！");
		}
		return "jsonResult";
	}
	
	/**
	 * 删除报销单以及相关的详单信息
	 */
	@Override
	public String remove() {
		if (getModel().getId() != null) {
			Reimb reimb = getManager().get(getModel().getId());
			getManager().reimbRemove(reimb);
		}
		return SUCCESS;
	}

	/**
	 * AjAX应用编辑报销明细页面，得到所有币种信息
	 * 
	 * @return
	 */
	public String getCurrencys() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		try {
			List<Currency> currencys = currencyManager.getCurrencyList();
			StringBuffer st = new StringBuffer();
			st.append("" + "," + "请选择..." + ":");
			for (Currency c : currencys) {
				st.append(c.getId() + "," + c.getName() + ":");
			}
			st.substring(0, st.length() - 1);
			jsonResult.put("result", st.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "jsonResult";
	}

	/**
	 * AjAX应用编辑报销明细页面，得到所有币种信息
	 * 
	 * @return
	 */
	public String getCurrencyRate() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		try {
			String currencyId = getRequest().getParameter("currencyId");
			if (StringUtils.isNotBlank(currencyId)) {
				ExchangeRate exchangeRate = exchangeRateManager.getExchangeRate(
						Integer.valueOf(currencyId), DateUtil.getYear());
				if (exchangeRate != null) {
					Map ratesMap = exchangeRateManager.getRatesMap(exchangeRate);
					Float rate = (Float) ratesMap.get(DateUtil.getMonth());
					if (rate != null) {
						jsonResult.put("result", rate.toString());
					} else {
						jsonResult.put("result", "failure");
					}
				}
			} else {
				jsonResult.put("result", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "jsonResult";
	}

	/**
	 * 选择出纳已付款的报销单列表【审批参考信息-业务员报销】
	 * 
	 * @return
	 */
	public String selfIndex() {
		StringBuffer hql = new StringBuffer("select rd.item.id, sum(rd.amount) from ReimbDetail rd where 1 = 1 ");
		List args = new ArrayList();
		hql.append(" and rd.reimb.reimber.id = ?");
		args.add(reimberId);
		commonReferenceCondition(hql, args);

		return "selfIndex";
	}

	/**
	 * 选择出纳已付款的报销单列表【审批参考信息-部门报销】
	 * 
	 * @return
	 */
	public String deptIndex() {
		StringBuffer hql = new StringBuffer(
				"select rd.item.id, sum(rd.amount) from ReimbDetail rd where rd.reimb.project.id is null ");
		List args = new ArrayList();
		hql.append(" and rd.reimb.dept.serialNo like ? ");
		args.add(MatchMode.START.toMatchString(getLoginUserDept().getSerialNo()));
		commonReferenceCondition(hql, args);
		return "deptIndex";
	}

	/**
	 * 选择出纳已付款的报销单列表【审批参考信息-项目报销】
	 * 
	 * @return
	 */
	public String projectIndex() {
		StringBuffer hql = new StringBuffer(
				"select rd.item.id, sum(rd.amount) from ReimbDetail rd where rd.reimb.project.id is not null ");
		List args = new ArrayList();
		hql.append(" and rd.reimb.project.id = ?");
		args.add(projectId);
		commonReferenceCondition(hql, args);
		return "projectIndex";
	}

	/**
	 * 选择出纳已付款的报销单列表【审批参考信息-财务查询所有】
	 * 
	 * @return
	 */
	public String financeIndex() {
		StringBuffer hql = new StringBuffer("select rd.item.id, sum(rd.amount) from ReimbDetail rd where 1 = 1 ");
		List args = new ArrayList();
		commonReferenceCondition(hql, args);
		return "financeIndex";
	}

	/**
	 * 公共的【报销参考】查询条件
	 * 
	 * @param hql
	 * @param args
	 */
	private void commonReferenceCondition(StringBuffer hql, List<Object> args) {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		hql.append(" and rd.reimb.payStatus = ?");
		args.add(Constants.YES);
		//hql.append(" order by rd.reimb.createDate ");
		hql.append(" group by rd.item.id order by rd.item.code");	
		page = getManager().pageQuery(page, hql.toString(), args.toArray());	
		List<ReimbDetail> rdList = page.getData();
    List<ReimbDetail> items = new ArrayList();
    double totalAmount = 0;
		for (Object o : rdList) {
			Object[] oo = (Object[]) o;
			ReimbDetail rd = new ReimbDetail();
			if (StringUtils.isNotBlank(oo[0].toString())) {
				rd.setItem(getManager().getDao().get(Item.class, Integer.valueOf(oo[0].toString())));
			}
      if (StringUtils.isNotBlank(oo[1].toString())) {
      	rd.setAmount(Double.valueOf(oo[1].toString()));
      }
      totalAmount = totalAmount + rd.getAmount();
      rd.setTotalAmount(totalAmount);
      items.add(rd);
		}
		page.setData(items);
		restorePageData(page);
	}

	/**
	 * 出纳待审查询条件封装,出纳操作
	 */
	public String cashierPayIndex() {
		StringBuffer hql = new StringBuffer("from Reimb r where r.parentReimb is null ");
		List<Object> args = new ArrayList<Object>();
		// 查询部门及财务审核都已通过的报销单
		hql.append("and r.audStatus = ? ");
		args.add(FlowConstants.AUDIT_PASS);
		// 根据付款状态查询
		if (StringUtils.isNotBlank(getModel().getPayStatus())) {
			hql.append("and r.payStatus = ? ");
			args.add(getModel().getPayStatus());
		}
		commonDateCondition(hql, args);
		hql.append("order by r.payStatus, r.createDate");
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		return "cashierPayIndex";
	}

	/**
	 * 异步调用,出纳支付【报销】
	 * 
	 * @return
	 */
	public String doPayReimb() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		User auditor = UserUtil.getPrincipal(getRequest());
		String reimbId = getRequest().getParameter("reimbId");
		String payType = getRequest().getParameter("payType");
		if (StringUtils.isNotBlank(reimbId)) {
			Reimb reimb = getManager().get(Integer.valueOf(reimbId));
			reimb.setPayStatus(Constants.YES);
			reimb.setPayType(payType);
			getManager().paySave(reimb, auditor);
			if (reimb.getChildReimbs().size() > 0 ) {
				for (Reimb childReimb : reimb.getChildReimbs()) {
					childReimb.setPayStatus(Constants.YES);
					childReimb.setPayType(payType);
					getManager().save(childReimb);
				}
			}
			jsonResult.put("result", "success");
		} else {
			jsonResult.put("result", "failure");
		}
		return "jsonResult";
	}

	// 获得关联部门
	private Dept getLoginUserDept() {
		User user = UserUtil.getLoginUser(getRequest());
		user = getManager().getDao().get(User.class, user.getId());
		Dept dept = user.getDept();
		if (dept == null) {
			throw new ApplicationException("无关联部门");
		}
		return dept;
	}

	/**
	 * 查看本部门报销审批信息
	 * @return
	 */
	public String view() {
		return VIEW;
	}
	
	/**
	 * 显示报销申请部门审批状态
	 */
	public Map<String, String> getAuditStatusMap() {
		return FlowConstants.APPLY_STATUS_MAP;
	}

	/**
	 * 出纳是否付款
	 */
	public Map<String, String> getPayStatusMap() {
		return FlowConstants.PAY_MAP;
	}

	/**
	 * 出纳支付方式
	 */
	public Map<String, String> getPayTypeMap() {
		return ReimbConstants.PAY_TYPE_MAP;
	}

	/**
	 * return
	 */

	public Map<String, String> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, String> jsonResult) {
		this.jsonResult = jsonResult;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public List<ProjectType> getProjectTypes() {
		return projectTypes;
	}

	public void setProjectTypes(List<ProjectType> projectTypes) {
		this.projectTypes = projectTypes;
	}

	public Integer getProjectTypeId() {
		return projectTypeId;
	}

	public void setProjectTypeId(Integer projectTypeId) {
		this.projectTypeId = projectTypeId;
	}

	public Integer getReimberId() {
		return reimberId;
	}

	public void setReimberId(Integer reimberId) {
		this.reimberId = reimberId;
	}

	public Integer getProjectId() {
		return projectId;
	}

	public void setProjectId(Integer projectId) {
		this.projectId = projectId;
	}

	public Integer getParentReimbId() {
		return parentReimbId;
	}

	public void setParentReimbId(Integer parentReimbId) {
		this.parentReimbId = parentReimbId;
	}

}
